# Import required modules
import tkinter as tk
from tkinter import ttk, messagebox
import json
import os
import sys
from pathlib import Path

# Style configuration (maintain original aesthetic style)
def setup_style():
    style = ttk.Style()
    style.configure("Main.TFrame", background="#f5f7fa")
    style.configure("Card.TFrame", background="white", borderwidth=1, relief="solid")
    style.configure("Primary.TButton", background="#4a90e2", foreground="#1e70ce", 
                   font=("Arial", 10, "bold"), padding=8)
    style.map("Primary.TButton", background=[("active", "#357abd")], 
             foreground=[("active", "white")])
    style.configure("Title.TLabel", font=("Arial", 14, "bold"), background="#f5f7fa", 
                   foreground="#333333")
    style.configure("Normal.TLabel", font=("Arial", 10), background="white", 
                   foreground="#555555")
    style.configure("TEntry", font=("Arial", 10), padding=8, borderwidth=1, relief="solid")

class LoginFrame(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent, style="Main.TFrame")
        self.parent = parent
        self.parent.title("LMS System Login")
        self.parent.geometry("800x600")
        self.parent.resizable(True, True)
        
        # Add project root directory to system path
        current_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.abspath(os.path.join(current_dir, ".."))
        sys.path.append(project_root)
        
        # Initialize style
        setup_style()
        
        # Store user data file path (matches project structure)
        self.user_data_path = Path(__file__).parent.parent / "Data" / "UserAccount.json"
        
        # Create login interface elements
        self._create_widgets()
    
    def _create_widgets(self):
        # Create login interface components
        # Login card (centered display)
        login_card = ttk.Frame(self, style="Card.TFrame", width=400, height=320)
        login_card.pack(expand=True, fill=None, anchor=tk.CENTER)
        login_card.pack_propagate(False)  # Fix card size
        
        # Title
        title_label = ttk.Label(login_card, text="LMS System Login", style="Title.TLabel")
        title_label.pack(pady=(30, 20))
        
        # Username input
        username_frame = ttk.Frame(login_card, style="Card.TFrame")
        username_label = ttk.Label(username_frame, text="Username:", style="Normal.TLabel")
        self.username_entry = ttk.Entry(username_frame, width=30)
        username_label.pack(side=tk.LEFT, padx=10, pady=5)
        self.username_entry.pack(side=tk.LEFT, padx=10, pady=5, fill=tk.X, expand=True)
        username_frame.pack(pady=5, fill=tk.X, padx=40)
        
        # Password input
        password_frame = ttk.Frame(login_card, style="Card.TFrame")
        password_label = ttk.Label(password_frame, text="Password:", style="Normal.TLabel")
        self.password_entry = ttk.Entry(password_frame, width=30, show="*")
        password_label.pack(side=tk.LEFT, padx=10, pady=5)
        self.password_entry.pack(side=tk.LEFT, padx=10, pady=5, fill=tk.X, expand=True)
        password_frame.pack(pady=5, fill=tk.X, padx=40)
        
        # User role selection
        role_frame = ttk.Frame(login_card, style="Card.TFrame")
        role_label = ttk.Label(role_frame, text="Role:", style="Normal.TLabel")
        self.role_var = tk.StringVar(value="Student")
        student_radio = ttk.Radiobutton(role_frame, text="Student", variable=self.role_var, value="Student")
        teacher_radio = ttk.Radiobutton(role_frame, text="Teacher", variable=self.role_var, value="Teacher")
        admin_radio = ttk.Radiobutton(role_frame, text="Admin", variable=self.role_var, value="Admin")
        role_label.pack(side=tk.LEFT, padx=10, pady=10)
        student_radio.pack(side=tk.LEFT, padx=5, pady=10)
        teacher_radio.pack(side=tk.LEFT, padx=5, pady=10)
        admin_radio.pack(side=tk.LEFT, padx=5, pady=10)
        role_frame.pack(pady=10, fill=tk.X, padx=40)
        
        # Login button
        login_btn = ttk.Button(login_card, text="Login", style="Primary.TButton", command=self.login)
        login_btn.pack(pady=10, fill=tk.X, padx=60)
        
        # Display current frame
        self.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
    
    def _load_user_data(self):
        # Load user data from JSON file, return user list (with exception handling)
        # Check if file exists
        if not self.user_data_path.exists():
            messagebox.showerror("Error", f"User data file does not exist:\n{self.user_data_path}")
            return None
        
        try:
            # Read and parse JSON
            with open(self.user_data_path, "r", encoding="utf-8") as f:
                user_list = json.load(f)
            
            # Validate JSON format (must be list and each user contains required fields)
            if not isinstance(user_list, list):
                raise ValueError("JSON data must be in list format")
            
            required_fields = ["id", "password", "role"]
            for user in user_list:
                if not isinstance(user, dict) or not all(field in user for field in required_fields):
                    raise ValueError(f"Invalid user data format: {user} missing required fields (id/password/role)")
            
            return user_list
            
        except json.JSONDecodeError:
            messagebox.showerror("Error", "Invalid JSON file format, cannot parse")
            return None
        except Exception as e:
            messagebox.showerror("Error", f"Failed to load user data: {str(e)}")
            return None
    
    def login(self):
        # Login verification (connect to JSON file)
        # 1. Get input
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        role = self.role_var.get()  # Values: Student/Teacher/Admin
        
        # 2. Basic input validation
        if not username or not password:
            messagebox.showerror("Error", "Username and password cannot be empty!")
            return
        
        if role not in ["Student", "Teacher", "Admin"]:
            messagebox.showerror("Error", "Please select a valid user role!")
            return
        
        # 3. Load user data
        user_list = self._load_user_data()
        if not user_list:  # Return directly if loading failed
            return
        
        # 4. Verify account password (filter by role)
        matched_user = None
        for user in user_list:
            # Role match + username match
            if user["role"] == role and user["id"] == username:
                matched_user = user
                break
        
        # 5. Result judgment
        if not matched_user:
            role_name = {"Student": "Student", "Teacher": "Teacher", "Admin": "Administrator"}[role]
            messagebox.showerror("Error", f"[{role_name}] Username does not exist: {username}")
        elif matched_user["password"] != password:
            messagebox.showerror("Error", "Incorrect password, please try again!")
        else:
            # Login successful
            role_name = {"Student": "Student", "Teacher": "Teacher", "Admin": "Administrator"}[role]
            messagebox.showinfo("Login Successful", f"Welcome, {username} ({role_name})!")
            
            # Jump to corresponding interface based on role
            if role == "Admin":
                # Destroy login window
                self.parent.destroy()
                
                # Dynamically import AdminUI to avoid circular imports
                from UI.admin import AdminUI
                
                # Create and run admin interface
                admin_ui = AdminUI(current_admin=username)
                admin_ui.run()
                
            elif role == "Student":
                # Destroy login window
                self.parent.destroy()
                
                # Dynamically import AdminUI to avoid circular imports
                from UI.studentui import LMSApp
                
                # Create and run student interface
                root = tk.Tk()
                app = LMSApp(root, username)  # Student ID
                root.mainloop()
                
            elif role == "Teacher":
                # Destroy login window
                self.parent.destroy()
                
                # Dynamically import AdminUI to avoid circular imports
                from UI.teacherui import LMSApp
                
                # Create and run teacher interface
                root = tk.Tk()
                app = LMSApp(root, username)  # Teacher ID
                root.mainloop()

# Main program entry
if __name__ == "__main__":
    root = tk.Tk()
    app = LoginFrame(root)
    root.mainloop()